<?php

class ReviewManager
{
	const TYPE_LIKE = 1;
	const TYPE_DISLIKE = 2;
	
	private $review;
	private $id;
	
	private $errors = array();
	
	public function __construct($review = null)
	{
		if($review != null){
			$this->setModel($review);
		}
	}
	
	public function setModel(Review $review)
	{
		$this->review = $review;
		$this->id = $review->id;
	}
	
	public function setModelById($id)
	{
		$this->setModel(Review::model()->findByPk($id));
	}
	
	public function refreshModel()
	{
		$this->setModel(Review::model()->findByPk($this->id));
	}
	
	public function getModel()
	{
		return $this->review;
	}
	
	public function addFeedback($feedback,$uid)
	{
		$type = ($feedback == 'like') ? 1 : 0;
		$transaction = Yii::app()->db->beginTransaction();
		try {
			$reviewFeedback = ReviewFeedback::model()->findByAttributes(array('uid'=>$uid, 'review_id' => $this->id));
			if($reviewFeedback == null){
				$reviewFeedback = new ReviewFeedback();
				$reviewFeedback->uid = Yii::app()->user->id;
				$reviewFeedback->review_id = $this->id;
				if($feedback == 'like'){
					$this->review->all_like = $this->review->all_like + 1;
				}
				else{
					$this->review->all_dislike = $this->review->all_dislike + 1;
				}
			}
			else{
				if($reviewFeedback->type == $type){
					if($reviewFeedback->type == 1){
						$this->review->all_like = $this->review->all_like - 1;
					}
					else{
						$this->review->all_dislike = $this->review->all_dislike - 1;
					}
						
				}
				else {
					if($_POST['type'] == 'like'){
						$this->review->all_like = $this->review->all_like + 1;
						$this->review->all_dislike = $this->review->all_dislike - 1;
					}
					else{
						$this->review->all_like = $this->review->all_like - 1;
						$this->review->all_dislike = $this->review->all_dislike + 1;
					}
				}
			}
				
			if($reviewFeedback->type == $type && !$reviewFeedback->isNewRecord){
				if(!$reviewFeedback->delete()){
					$this->errors[] = $reviewFeedback->getErrors();
					throw new Exception('feedback not delete.');
				}
			}
			else{
				$reviewFeedback->type = $type;
				if(!$reviewFeedback->save()){
					$this->errors[] = $reviewFeedback->getErrors();
					throw new Exception('feedback not save.');
				}
			}
			if(!$this->review->save()){
				$this->errors[] = $this->review->getErrors();
				throw new Exception('review not save.');
			}
			$transaction->commit();
		}
		catch(Exception $e) {
			$transaction->rollback();
			$this->errors[] = $e;
			return false;
		}
		return true;
	}
}